package com.gzc.just.play.last.war.gateserver;

import com.gzc.just.play.last.war.common.handler.VirtualThreadNettyServer;
import com.gzc.just.play.last.war.common.handler.VirtualThreadServerFramework;
import com.gzc.just.play.last.war.gateserver.handler.*;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.context.annotation.DependsOn;

/**
 * Gate Server的Netty服务器实现
 * 使用虚拟线程处理网关服务器请求
 */
@Component("gateNettyServer")
public class GateNettyServer extends VirtualThreadNettyServer {
    private static final Logger logger = LoggerFactory.getLogger(GateNettyServer.class);

    @Value("${gate.server.port:40001}")
    private int gateServerPort;
    
    @Value("${gate.server.host:127.0.0.1}")
    private String gateServerHost;
    
    @Autowired
    private ApplicationContext applicationContext;
    
    public GateNettyServer() {
        logger.info("GateNettyServer bean is being constructed");
    }
    
    @Override
    protected int getNettyPort() {
        return gateServerPort;
    }
    
    @Override
    protected String getNettyHost() {
        return gateServerHost;
    }

    @Override
    protected VirtualThreadServerFramework.ServerType getServerType() {
        return VirtualThreadServerFramework.ServerType.GATE_SERVER;
    }
    
    @Override
    protected void initializeHandlers() {
        try {
            // 从Spring容器中获取Bean，而不是直接new
            if (applicationContext != null) {
                SimpleLoginHandler simpleLoginHandler = applicationContext.getBean(SimpleLoginHandler.class);
                framework.registerHandler(simpleLoginHandler);
                
                ClientConnectionHandler clientConnectionHandler = applicationContext.getBean(ClientConnectionHandler.class);
                framework.registerHandler(clientConnectionHandler);

                OrderPostToGCHandler orderPostToGCHandler = applicationContext.getBean(OrderPostToGCHandler.class);
                framework.registerHandler(orderPostToGCHandler);
                
                logger.info("Initialized {} handlers for Gate Server from Spring context", framework.getHandlerManager().getHandlerCount());
            } else {
                logger.warn("ApplicationContext not available, using direct instantiation for handlers");
                // 降级方案：如果无法从容器获取，直接实例化
                framework.registerHandler(new SimpleLoginHandler());
                framework.registerHandler(new ClientConnectionHandler());
                framework.registerHandler(new OrderPostToGCHandler());
                
                logger.info("Initialized {} handlers for Gate Server using direct instantiation", framework.getHandlerManager().getHandlerCount());
            }
        } catch (Exception e) {
            logger.error("Error initializing Gate Server handlers", e);
            throw new RuntimeException("Failed to initialize Gate Server handlers", e);
        }
    }
    
    @Override
    protected void onConnectionActive(ChannelHandlerContext ctx) {
        super.onConnectionActive(ctx);
        // Gate Server特有的连接处理逻辑
        logger.debug("New gate connection from: {}", ctx.channel().remoteAddress());
    }
    
    @Override
    protected void onConnectionInactive(ChannelHandlerContext ctx) {
        super.onConnectionInactive(ctx);
        // Gate Server特有的连接关闭处理逻辑
        logger.debug("Gate connection closed from: {}", ctx.channel().remoteAddress());
    }

    /**
     * 获取客户端连接
     */
    public ChannelHandlerContext getClientConnection(long sessionId) {
        return activeConnections.get(sessionId);
    }
}